<template>
  <div class="app-container">
    <el-card>
      <div slot="header" style="display:flex;align-items: center;justify-content: space-between;">
        <span>商品分类</span>
        <el-button type="success" icon="el-icon-plus" size="small" @click="handleAddCate">添加分类</el-button>
      </div>
      <!-- 表格主体 -->
      <div class="table-wrapper">
        <el-table height="80vh" :data="tableData" row-key="id" style="width: 100%" :row-class-name="tableRowClassName" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column prop="categoryName" label="类目名称" />
          <el-table-column prop="lib" label="类别">
            <template slot-scope="scope">
              <span>{{ scope.row.parentCategoryCode === '#' ? `一级目录` : `二级目录` }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="categoryPic" label="图标">
            <template slot-scope="scope">
              <img :src="scope.row.categoryPic" style="width:32px">
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" />
          <el-table-column prop="state" label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button class="red" type="text" @click="handleDelCate(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 弹窗提示 -->
    <el-dialog :visible.sync="dialogFormVisible" :destroy-on-close="true" width="50%" :title="form.ifEdit ? '编辑分类' : '新增分类'" :before-close="onCloseDialog">
      <el-form ref="ruleForm" :rules="rules" :model="form">
        <!-- 上级分类 -->
        <el-form-item required label="上级分类" :label-width="formLabelWidth">
          <el-select style="width:100%" v-model="form.parentCategoryCode" placeholder="请选择状态">
            <el-option label="一级目录" :value="null" />
            <el-option v-for="row in tableData" :key="row.categoryCode" :label="row.categoryName" :value="row.categoryCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth">
          <el-input-number v-model="form.sort" controls-position="right" :min="0"></el-input-number>
        </el-form-item>
        <!-- 分类名称 -->
        <el-form-item required label="分类名称" :label-width="formLabelWidth" prop="categoryName">
          <el-input v-model="form.categoryName" autocomplete="off" placeholder="请输入分类名称" clearable />
        </el-form-item>
        <!-- 状态 -->
        <el-form-item required label="分类状态" :label-width="formLabelWidth">
          <el-select style="width:100%" v-model="form.active" placeholder="请选择状态">
            <el-option label="上架" value="1" />
            <el-option label="下架" value="0" />
          </el-select>
        </el-form-item>
        <!-- 分类模版 -->
        <el-form-item required label="分类模版" :label-width="formLabelWidth" prop="typeId">
          <el-select style="width:100%" v-model="form.typeId" placeholder="请输入关键词" filterable>
            <el-option v-for="item in form.typeTemplatOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item required label="上传图标" :label-width="formLabelWidth">
          <!-- 图片上传组件 -->
          <UploadImage :defaultList.sync="form.fileList" ref="UploadImage" color="#1890ff" class="editor-upload-btn" @delCallBack="imageSuccess" @successCBK="imageSuccess" />
          <!-- tips -->
          <i style="color: #909399;">建议上传尺寸: 70*70</i>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="onClickSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UploadImage from '@/components/UploadImage/UploadImage';
export default {
  name: 'Category',
  data() {
    return {
      dialogFormVisible: false,
      formLabelWidth: '80px',
      dialogImageUrl: '',
      disabled: false,
      tableData: [],
      // 表达校验规则
      rules: {
        categoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
        order: [{ required: true, message: '请输入序号', trigger: 'blur' }],
        typeId: [
          { required: true, message: '请选择分类模版', trigger: 'blur' },
        ],
      },
      // 表单数据
      form: {
        parentCategoryCode: null, // 父级分类
        categoryName: '',
        sort: 0,
        active: '1',
        order: '',
        fileList: [],
        ifEdit: false, // 是否是编辑状态
        categoryList: [], // 父级目录
        typeId: null, // 分类模版
        typeName: '', // 分类模版
        typeTemplatOptions: [], // 分类模版选项列表
      },

      loading: false, // 分类模版loading
    };
  },
  // watch: {
  //   dialogFormVisible() {
  //     this.$refs['ruleForm'] && this.$refs['ruleForm'].resetFields();
  //   },
  // },
  mounted() {
    this.init();
  },
  components: {
    UploadImage,
  },
  methods: {
    tableRowClassName({ rowIndex }) {
      switch (rowIndex) {
        case 1:
          return 'warning-row';
        case 3:
          return 'success-row';
        default:
          return '';
      }
    },
    imageSuccess(arr) {
      this.form.fileList = arr;
    },
    init() {
      this.getCategoryList();
    },
    // 重制表单
    resetForm() {
      this.dialogFormVisible = false;
      this.$refs['ruleForm'].resetFields();
      this.$refs.UploadImage.RemovePrevFileList();
      this.form.fileList = [];
    },
    // 表单提交
    onClickSubmit() {
      console.log('this.form', this.form);
      this.$refs['ruleForm'].validate(async (valid) => {
        if (!valid) return;

        const { fileList, ifEdit } = this.form;
        if (fileList.length < 1) return;

        if (ifEdit) {
          this.editCategory();
        } else {
          this.addCategory();
        }
        // // 关闭弹窗
        // this.resetForm()
        // // 重新请求列表
        // setTimeout(() => {
        //     this.getCategoryList()
        // }, 100)
      });
    },

    /**
     * 关闭弹窗
     */
    onCloseDialog(done) {
      this.form = {
        parentCategoryCode: null, // 父级分类
        categoryName: '',
        sort: 0,
        active: '1',
        order: '',
        fileList: [],
        ifEdit: false, // 是否是编辑状态
        categoryList: [], // 父级目录
        typeId: null, // 分类模版
        typeName: '', // 分类模版
        typeTemplatOptions: [], // 分类模版选项列表
      };
      done();
    },
    // 编辑表单
    handleEdit(row) {
      const fileList = [{ url: row.categoryPic }];
      this.form = Object.assign({}, this.form, row, { fileList, ifEdit: true });
      this.dialogFormVisible = true;
      this.getTemplate();
    },
    // 删除分类
    async handleDelCate({ id }) {
      const confirm = await this.$confirm(
        '此操作将永久删除该分类，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch(() => {});

      confirm && this.deleteCategory(id);
    },
    // 添加分类
    handleAddCate() {
      this.dialogFormVisible = true;
      this.form = Object.assign({}, this.form, { ifEdit: false });
      this.getTemplate();
    },

    async getCategoryList() {
      const response = await this.$api.getCategoryList();
      const { data } = response;
      this.tableData = data;
    },
    async addCategory() {
      const {
        categoryName,
        sort,
        active,
        fileList,
        parentCategoryCode,
        typeId,
      } = this.form;
      const response = await this.$api.addCategoryList({
        categoryName,
        sort,
        merchantId: this.$store.getters.customerId,
        active: active,
        categoryPic: fileList[0].url,
        parentCategoryCode,
        typeId: typeId,
      });
      if (response.success) {
        this.$message.success('添加成功');
        this.dialogFormVisible = false;
        this.getCategoryList();
      }
    },
    async editCategory() {
      const {
        active,
        categoryCode,
        categoryName,
        sort,
        merchantId,
        id,
        fileList,
        parentCategoryCode,
        typeId,
      } = this.form;
      const response = await this.$api.setCategory({
        active,
        merchantId,
        categoryCode,
        id,
        categoryName,
        sort,
        categoryPic: fileList[0].url,
        parentCategoryCode,
        typeId,
      });
      if (response.success) {
        this.$message.success('编辑成功');
        this.dialogFormVisible = false;
        this.getCategoryList();
      }
    },
    async getTemplate(query) {
      if (query !== '') {
        this.loading = true;
        const params = {
          name: query,
        };
        if (params.name === undefined) delete params.name;
        const response = await this.$api.getTypeTemplateWithOutPagenation(
          params
        );
        this.form.typeTemplatOptions = response.data.map((e) => {
          return { id: e.id, name: e.name };
        });

        this.loading = false;
      } else {
        this.form.typeTemplatOptions = [];
      }
    },
    async deleteCategory(id) {
      const { success } = await this.$api.deleteCategory({ id });
      if (success) {
        this.$message.success('删除成功');
        // 重新请求列表
        this.getCategoryList();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  & /deep/ .el-table {
    .warning-row {
      background: #fff;
    }
    .success-row {
      background: #fff;
    }
  }
  .icon-cell {
    font-size: 24px;
    cursor: pointer;
  }
}
</style>
